﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;

namespace System.Data.SugarClient
{

	public class SugarConnectionStringBuilder : DbConnectionStringBuilder
	{

		public SugarConnectionStringBuilder()
		{
			this.ApplicationName = SugarConnectionOption.DEFAULT.ApplicationName;
			this.ConnectionTimeout = SugarConnectionOption.DEFAULT.ConnectionTimeout;
			this.DataSource = SugarConnectionOption.DEFAULT.DataSource;
			this.UserID = SugarConnectionOption.DEFAULT.UserID;
			this.Password = SugarConnectionOption.DEFAULT.Password;
			this.EncryptionKey = SugarConnectionOption.DEFAULT.EncryptionKey;
			this.PageSize = SugarConnectionOption.DEFAULT.PageSize;
		}

		public string ApplicationName
		{
			get { return GetString(SugarConnectionOption.Keywords.ApplicationName); }
			set
			{ 
				this[SugarConnectionOption.Keywords.ApplicationName] = value;
			}
		}

		public int ConnectionTimeout
		{
			get { return GetInt32(SugarConnectionOption.Keywords.ConnectionTimeout, SugarConnectionOption.DEFAULT.ConnectionTimeout); }
			set
			{
				this[SugarConnectionOption.Keywords.ConnectionTimeout] = value;
			}
		}

		public string DataSource
		{
			get { return GetString(SugarConnectionOption.Keywords.DataSource); }
			set
			{
				this[SugarConnectionOption.Keywords.DataSource] = value;
			}
		}

		public string UserID
		{
			get { return GetString(SugarConnectionOption.Keywords.UserID); }
			set
			{
				this[SugarConnectionOption.Keywords.UserID] = value;
			}
		}

		public string Password
		{
			get { return GetString(SugarConnectionOption.Keywords.Password); }
			set
			{
				this[SugarConnectionOption.Keywords.Password] = value;
			}
		}

		public string EncryptionKey
		{
			get { return GetString(SugarConnectionOption.Keywords.EncryptionKey); }
			set
			{
				this[SugarConnectionOption.Keywords.EncryptionKey] = value;
			}
		}

		public int PageSize
		{
			get { return GetInt32(SugarConnectionOption.Keywords.PageSize, SugarConnectionOption.DEFAULT.PageSize); }
			set
			{
				this[SugarConnectionOption.Keywords.PageSize] = value;
			}
		}

		public override object this[string keyword]
		{
			get { return base[keyword]; }
			set
			{
				Trace.Debug("SugarConnectionStringBuilder[\"{0}\"] = {1};", keyword, value);
				base[keyword] = value;
			}
		}

		private string GetString(string key)
		{
			if (this.ContainsKey(key)) return this[key].ToString();
			else return null;
		}

		private int GetInt32(string key, int defaultvalue)
		{
			if (this.ContainsKey(key))
			{
				object value = this[key];
				if (value is int) return (int)value;
				else return int.Parse(value.ToString());
			}
			else
			{
				return defaultvalue;
			}
		}
	}

}
